
import { _decorator, Component, Node, Button, Sprite, UITransform, Label, SpriteFrame, math, UIOpacity, Prefab, LightingStage, v3 } from 'cc';
import Action3dManager, { ActionMngType } from '../../Script/Common/Action3dManager';
import GameData from '../../Script/Common/GameData';
import GlobalData from '../../Script/Common/GlobalData';
import GlobalPool, { customPoolScript } from '../../Script/Common/GlobalPool';
import Loader from '../../Script/Common/Loader';
import PlayerData from '../../Script/Common/PlayerData';
import yyComponent from '../../Script/Common/yyComponent';
import { EventType } from '../../Script/GameSpecial/GameEventType';
import { GlobalEnum } from '../../Script/GameSpecial/GlobalEnum';
import { AwardItem } from './AwardItem';
const { ccclass, property } = _decorator;

@ccclass('SpinUI')
export class SpinUI extends yyComponent {
    /**场景/UI类型 */
    public get uiType() { return GlobalEnum.UI.spin; }


    //#region 脚本流程
    public init(data?) {
        if (undefined !== data) {
            this.setData(data);
        }
        this.initAwardTable();

    }
    protected setData(data) {

    }
    public reset() {

    }

    public show(data?: { data: any, config: any }) {
        this.reset();
        this.node.active = true;
        if (undefined !== data && undefined !== data.data) {
            this.setData(data.data);
        }
        this.resetDial();
        this.awardNode.active = false;
        this.emit(EventType.LevelEvent.changeGoldPos, false);
    }

    stepTime = 0;
    update(dt) {
        this.stepTime += dt;
        if (this.stepTime >= 30) {
            this.stepTime = 0;
            this.stepMinute();
        }

    }

    @property(Label)
    timeLab: Label = null;
    stepMinute() {
        this.updateBtnFreeSpin();
    }
    isFree: boolean = false;
    updateBtnFreeSpin() {
        let lastTime = PlayerData.getData("gameData.lastFreeTime");
        let T = new Date;
        let nowTime = T.getTime();
        let time = 420 - ((nowTime - lastTime) / 1000 / 60);
        if (time <= 0) {
            // this.timeLab.string = "免费";
            this.timeLab.node.active = false;
            this.btnSpin.node.getComponent(Sprite).spriteFrame = this.btnSprs[0];
            this.isFree = true;
        } else {
            let hour = Math.floor(time / 60);
            let min = Math.floor(time % 60);
            this.timeLab.node.active = true;
            this.timeLab.string = hour.toString() + "小时" + min.toString() + "分后免费";
            this.btnSpin.node.getComponent(Sprite).spriteFrame = this.btnSprs[1];
            this.isFree = false;
        }
        this.btnSpin.node.getComponent(UIOpacity).opacity = 255;
        this.btnSpin.interactable = true;
    }

    @property(Prefab)
    awardItem: Prefab = null;
    awardItems: AwardItem[] = [];
    @property(Node)
    dialNode: Node = null;
    initAwardTable() {
        GlobalPool.createPool(this.awardItem.data.name, this.awardItem, this.awardItem.data.name);
        for (let i = 0; i < 8; i++) {
            let newItem = GlobalPool.get(this.awardItem.data.name);
            this.dialNode.addChild(newItem);
            newItem.angle = i * (-45);
            this.awardItems.push(newItem[customPoolScript]);
        }
    }

    /**轮盘奖品更新与显示 */
    //#region 
    countAward = {
        tip: [3, 5, 20],
        "3": {
            "id": 5,
            "goodsType": "hat",
        },
        "8": {
            "id": 16,
            "goodsType": "skin",
        },
        "20": {
            "id": 18,
            "goodsType": "skin",
        }
    }
    spinAward = [{
        "id": 6,
        "goodsType": "hat",
    }, {
        "id": 7,
        "goodsType": "hat",
    }, {
        "id": 8,
        "goodsType": "hat",
    }]
    prizes = [];
    spinCount = 0;
    public fillPrize() {
        this.findSpinGoods();
        this.setCountAward();
        this.setSpinAward();
    }
    //加载剩余奖品与抽奖次数；
    protected findSpinGoods() {
        this.prizes = [];
        let playerHatData = PlayerData.getData("gameData.HatSkin.owned");
        for (let i = 0; i < this.spinAward.length; i++) {
            let index = playerHatData.indexOf(this.spinAward[i]["id"]);
            if (index < 0) {
                this.prizes.push(this.spinAward[i]);
            }
        }
        this.spinCount = PlayerData.getData("gameData.spinCount");
    }
    //次数奖励
    @property(Node)
    bar: Node = null;
    @property(Label)
    countLabel: Label = null;
    @property([Sprite])
    img: Sprite[] = [];
    @property(SpriteFrame)
    getedImg: SpriteFrame = null;
    protected setCountAward() {
        let leng = this.bar.getComponent(Sprite).spriteFrame.originalSize.width;
        let rate = this.spinCount / 20;
        if (rate > 1) {
            rate = 1;
        }
        this.bar.getComponent(UITransform).width = leng * rate;
        this.countLabel.string = this.spinCount.toString();
        if (this.spinCount >= 3) {
            this.img[0].spriteFrame = this.getedImg;
            if (this.spinCount >= 8) {
                this.img[1].spriteFrame = this.getedImg;
                if (this.spinCount >= 20) {
                    this.img[2].spriteFrame = this.getedImg;
                }
            }
        }
    }
    protected setSpinAward() {
        while (this.prizes.length != 8) {
            if (this.prizes.length > 8) {
                this.prizes.pop();
            } else {
                this.prizes.push({
                    "value": this.getRandomGold(),
                    "goodsType": "gold",
                })
            }
        }
        this.prizes = this.randomArry(this.prizes);

        for (let i = 0; i < this.prizes.length; i++) {
            let data = this.prizes[i];
            this.awardItems[i].setData(data);
        }
    }
    //随机200-1000的数
    protected getRandomGold() {
        return (Math.floor(Math.random() * 9) + 2) * 100;
    }
    //将arr数组随机乱序
    protected randomArry(arr) {
        let leng = arr.length;
        let numArry = [];
        for (let i = 0; i < leng; i++) {
            numArry.push(i);
        }
        let outArry = [];
        for (let i = 0; i < 8; i++) {
            let index = Math.floor(Math.random() * numArry.length)
            let index2 = numArry.splice(index, 1)[0];
            outArry.push(arr[index2]);
        }
        return outArry;
    }
    //#endregion

    mng = null;
    @property(Node)
    awardNode: Node = null;
    @property(Sprite)
    awardSpr: Sprite = null;
    resetDial() {
        this.dialNode.angle = 0;
        if (!this.mng) {
            this.mng = Action3dManager.getMng(ActionMngType.UI);
        }
        this.mng.stopAllActions(this.dialNode);
        this.fillPrize();
        this.resetBtn();
    }

    rotateDial() {
        this.unableBtn();

        let randomCount = this.getRandomAngle();
        let rotate1 = Action3dManager.rotateTo2d(3, randomCount * 360);
        rotate1.easing(Action3dManager.easeInOut(2));
        let callFun = Action3dManager.callFun(this.getAward, this, randomCount);
        let sequen = Action3dManager.sequence(rotate1, callFun);
        this.mng.runAction(this.dialNode, sequen);
        this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.spin);
    }
    delay = null;
    getAward(count) {
        let index = Math.floor((count - Math.floor(count)) * 8);
        let award = this.prizes[index];
        this.addSpinCount();
        let playerCount = PlayerData.getData("gameData.spinCount");
        if (playerCount == 3 || playerCount == 8 || playerCount == 20) {
            if (playerCount == 3) {
                this.awardNode.active = true;
                this.awardSpr.spriteFrame = this.img[0].node.children[0].getComponent(Sprite).spriteFrame;
                this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
                    attribute: "gameData.HatSkin.owned",
                    value: 4,
                    mode: "push",
                    emit: true,
                    save: true,
                });
            } else if (playerCount == 8) {
                this.awardNode.active = true;
                this.awardSpr.spriteFrame = this.img[1].node.children[0].getComponent(Sprite).spriteFrame;
                this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
                    attribute: "gameData.PlayerSkin.owned",
                    value: 16,
                    mode: "push",
                    emit: true,
                    save: true,
                });
            } else if (playerCount == 20) {
                this.awardNode.active = true;
                this.awardSpr.spriteFrame = this.img[2].node.children[0].getComponent(Sprite).spriteFrame;
                this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
                    attribute: "gameData.PlayerSkin.owned",
                    value: 18,
                    mode: "push",
                    emit: true,
                    save: true,
                });
            }
            this.delay = { award: award, index: index };
        } else {
            this.addAward(award, index);
            this.delay = null;
        }
    }
    addAward(data, index) {
        if (data["goodsType"] == "gold") {
            this.addGold(data["value"], index, () => {
                this.resetDial();
                this.resetBtn();
            })
        } else if (data["goodsType"] == "hat") {
            this.emit(EventType.Common.AudioEvent.playEffect, GlobalEnum.AudioClip.getSkin);
            this.awardNode.active = true;
            this.awardSpr.spriteFrame = this.awardItems[index].spr.spriteFrame;
            this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
                attribute: "gameData.HatSkin.owned",
                value: data["id"],
                mode: "push",
                emit: true,
                save: true,
            });
        }
    }

    /**播放金币动画获得金币 */
    protected addGold(gold: number, index: number, cb?: Function) {
        let pos = this.awardItems[index].node.getComponent(UITransform).convertToWorldSpaceAR(v3(0, 0, 0));
        let cvs = GlobalData.get(GlobalEnum.Common.GlobalDataType.canvasTransform);
        pos.x -= cvs.width * 0.5;
        pos.y -= cvs.height * 0.5;
        this.emit(EventType.Common.UIEvent.playGoldAnim, {
            // startPos: pos,
            cb: () => {
                this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
                    attribute: "gameData.asset.gold",
                    value: gold,
                    mode: "+",
                    emit: true,
                    save: true,
                });
                !!cb && cb();
            },
            gold: gold,
        })
    }
    //获取10-15之间的一个随机数
    getRandomAngle() {
        let x = Math.random() * 5;
        return 5 + x;
    }
    //增加玩家抽奖次数
    addSpinCount() {
        this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
            attribute: "gameData.spinCount",
            value: 1,
            mode: "+",
            emit: true,
            save: true,
        });
    }

    @property(Button)
    btnSpin: Button = null;
    @property(Button)
    btnBack: Button = null;
    @property([SpriteFrame])
    btnSprs: SpriteFrame[] = [];
    resetBtn() {
        this.btnBack.interactable = true;
        this.updateBtnFreeSpin();
    }
    unableBtn() {
        this.btnSpin.interactable = false;
        this.btnSpin.node.getComponent(UIOpacity).opacity = 100;
        this.btnBack.interactable = false;
    }

    protected onBtnSpin() {
        this.playClickBtn();
        if (!!this.isFree) {
            this.freeSpin();
        } else {
            this.videoSpin();
        }
    }

    protected freeSpin() {
        let T = new Date;
        let nowTime = T.getTime();
        this.emit(EventType.Common.PlayerDataEvent.updatePlayerData, {
            attribute: "gameData.lastFreeTime",
            value: nowTime,
            mode: "=",
            emit: true,
            save: true,
        });
        this.rotateDial();
    }
    protected videoSpin() {
        this.emit(EventType.Common.SDKEvent.showVideo, {
            success: () => {
                this.rotateDial();
            },
        });
    }
    protected onBtnExitAward() {
        this.playClickBtn();
        this.awardNode.active = false;
        if (this.delay) {
            this.addAward(this.delay["award"], this.delay["index"]);
            this.delay = null;
            return;
        }
        this.resetDial();
        this.resetBtn();
    }
    protected onBtnExit() {
        this.playClickBtn();
        this.emit(EventType.Common.UIEvent.exit, this.uiType);
        this.emit(EventType.LevelEvent.changeGoldPos, true);
    }
}